package com.talent.service.impl;

import com.talent.config.FileProperties;
import com.talent.handler.BaseException;
import com.talent.mapper.FileMapper;
import com.talent.pojo.entity.FileInfo;
import com.talent.pojo.vo.FileUploadVO;
import com.talent.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件服务实现类
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileProperties fileProperties;

    @Autowired
    private FileMapper fileMapper;

    /**
     * 上传文件
     */
    @Override
    public FileUploadVO uploadFile(MultipartFile file, String type) {
        if (file.isEmpty()) {
            throw new BaseException("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new BaseException("文件名不能为空");
        }

        // 获取文件扩展名
        String extension = StringUtils.getFilenameExtension(originalFilename);
        if (extension == null) {
            throw new BaseException("文件扩展名不能为空");
        }

        // 生成新的文件名
        String fileName = UUID.randomUUID().toString() + "." + extension;
        
        // 创建日期目录
        String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String relativePath = dateDir + "/" + fileName;
        
        // 完整的文件路径
        String uploadPath = fileProperties.getUploadPath();
        String fullPath = uploadPath + relativePath;
        
        try {
            // 创建目录
            File destFile = new File(fullPath);
            File parentDir = destFile.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }

            // 保存文件
            file.transferTo(destFile);

            // 保存文件信息到数据库
            FileInfo fileInfo = new FileInfo();
            fileInfo.setFilename(fileName);
            fileInfo.setOriginalName(originalFilename);
            fileInfo.setUrl("/api/files/" + relativePath);
            fileInfo.setType(type);
            fileInfo.setSize(file.getSize());

//            fileMapper.insert(fileInfo);

            // 返回结果
            FileUploadVO result = new FileUploadVO();
            result.setUrl(fileInfo.getUrl());
            result.setFilename(fileName);
            result.setSize(file.getSize());

            return result;
        } catch (IOException e) {
            throw new BaseException("文件上传失败");
        }
    }
}
